package cn.zj.logistics.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.zj.logistics.pojo.MessageObject;
import cn.zj.logistics.pojo.Role;
import cn.zj.logistics.pojo.RoleExample;
import cn.zj.logistics.pojo.User;
import cn.zj.logistics.pojo.UserExample;
import cn.zj.logistics.pojo.UserExample.Criteria;
import cn.zj.logistics.service.RoleService;
import cn.zj.logistics.service.UserService;

@Controller
@RequestMapping("/admin")
public class AdminController {

	@Autowired
	private UserService userService;

	@Autowired
	private RoleService roleService;

	
	
	
	@RequestMapping("/login")
	public String login(HttpServletRequest request,Model m) {
		
		//获取认证失败错误信息
		String shiroLoginFailure = (String) request.getAttribute("shiroLoginFailure");
		
		if(UnknownAccountException.class.getName().equals(shiroLoginFailure)) {
			m.addAttribute("errorMsg", "亲，账号错误");
		}else if(IncorrectCredentialsException.class.getName().equals(shiroLoginFailure)) {
			m.addAttribute("errorMsg", "亲，密码错误");
		}
		
		
		System.out.println("AdminController.login()");
		return "forward:/login.jsp";
	}
	
	
	
	
	// 跳转到 admin 管理页面
	@RequiresPermissions("admin:adminPage")
	@RequestMapping("/adminPage")
	public String adminPage() {
		return "adminPage";
	}

	@RequiresPermissions("admin:update")
	@ResponseBody
	@RequestMapping("/update")
	public MessageObject update(User user) {

		/*
		 * 设置密码加密 Shiro ： 原密码 +盐（随机数） MD5 加密三次
		 */
		// 使用UUID的5位作为salt
		String salt = UUID.randomUUID().toString().substring(0, 5);
		// 加密
		Md5Hash newPassword = new Md5Hash(user.getPassword(), salt, 3);

		// 将密新密码和盐设置user对象
		user.setSalt(salt);
		user.setPassword(newPassword.toString());

		int row = userService.updateByPrimaryKeySelective(user);

		MessageObject mo = MessageObject.creatMO(0, "修改数据失败，请联系管理员");
		if (row == 1) {
			mo = MessageObject.creatMO(1, "修改数据成功");
		}

		return mo;

	}

	@ResponseBody
	@RequestMapping("/insert")
	@RequiresPermissions("admin:insert")
	public MessageObject insert(User user) {

		// 设置日期
		user.setCreateDate(new Date());

		/*
		 * 设置密码加密 Shiro ： 原密码 +盐（随机数） MD5 加密三次
		 */
		// 使用UUID的5位作为salt
		String salt = UUID.randomUUID().toString().substring(0, 5);
		// 加密
		Md5Hash newPassword = new Md5Hash(user.getPassword(), salt, 3);

		// 将密新密码和盐设置user对象
		user.setSalt(salt);
		user.setPassword(newPassword.toString());

		int row = userService.insert(user);

		MessageObject mo = MessageObject.creatMO(0, "新增数据失败，请联系管理员");
		if (row == 1) {
			mo = MessageObject.creatMO(1, "新增数据成功");
		}

		return mo;

	}

	/*
	 * jackson+@ResponseBody 方法直接返回json格式的数据
	 * 
	 */

	@ResponseBody
	@RequiresPermissions("admin:list")
	@RequestMapping("/list")
	public PageInfo<User> list(@RequestParam(defaultValue = "1") Integer pageNum,
			@RequestParam(defaultValue = "10") Integer pageSize, String keyword) {
		PageHelper.startPage(pageNum, pageSize);

		UserExample example = new UserExample();

		// 开始条件查询
		if (StringUtils.isNotBlank(keyword)) {

			// 账号和真实姓名的模糊查询，OR 或者根据角色名称查
			Criteria criteria1 = example.createCriteria();
			criteria1.andUsernameLike("%" + keyword + "%");

			Criteria criteria2 = example.createCriteria();
			criteria2.andRealnameLike("%" + keyword + "%");

			// OR
			example.or(criteria2);

			Criteria criteria3 = example.createCriteria();
			criteria3.andRolenameLike("%" + keyword + "%");
			// OR
			example.or(criteria3);

		}

		List<User> users = userService.selectByExample(example);

		PageInfo<User> pageInfo = new PageInfo<>(users);

		return pageInfo;
	}

	@ResponseBody
	@RequiresPermissions("admin:delete")
	@RequestMapping("/delete")
	public MessageObject delete(Long userId) {

		int row = userService.deleteByPrimaryKey(userId);

		MessageObject mo = MessageObject.creatMO(0, "删除数据失败，请联系管理员！！");

		// 删除成功
		if (row == 1) {
			mo = MessageObject.creatMO(1, "删除数据成功！！！");
		}

		return mo;
	}

	// 批量删除功能
	@ResponseBody
	@RequiresPermissions("admin:delete")
	@RequestMapping("/batchDelete")
	public MessageObject batchDelete(String userIds) {

		/*
		 * 字符串切割
		 */
		String[] userIdsArr = userIds.split(",");
		List<Long> userIdsByList = new ArrayList<Long>();
		for (String userId : userIdsArr) {
			userIdsByList.add(Long.valueOf(userId));
		}

		UserExample example = new UserExample();
		Criteria criteria = example.createCriteria();
		criteria.andUserIdIn(userIdsByList);
		int rows = userService.deleteByExample(example);

		MessageObject mo = MessageObject.creatMO(0, "删除数据失败，请联系管理员！！");

		// 删除成功
		if (rows > 0) {
			mo = MessageObject.creatMO(1, "删除数据成功！！！");
		}

		return mo;
	}

	/*
	 * 新增或者修改跳转的编辑页面
	 * 
	 */

	@RequestMapping("/adminEdit")
	public String adminEdit(Model m, Long userId) {

		/*
		 * 如果是修改，有userId，要根据id查询出对应的管理员并共享让jsp页面回显
		 */
		if (userId != null) {
			System.out.println("AdminController.adminEdit()");
			User user = userService.selectByPrimaryKey(userId);
			m.addAttribute("user", user);
		}

		// 查询出所有角色并共享给编辑页面
		RoleExample example = new RoleExample();
		List<Role> roles = roleService.selectByExample(example);

		m.addAttribute("roles", roles);

		return "adminEdit";
	}

	@RequestMapping("/checkUsername")
	@ResponseBody
	public boolean checkUsername(String username) {

		UserExample example = new UserExample();
		Criteria criteria = example.createCriteria();
		criteria.andUsernameEqualTo(username);

		List<User> users = userService.selectByExample(example);

		return users.size() == 0 ? true : false;
	}

	@Test
	public void testName() throws Exception {

		/*
		 * 
		 * Java语言不能满足实际开发中的一些特殊需求，如判断字符串为空，数组可以向像集合一样add，get
		 * 
		 * Apache 组织为Java语言写一个增强包各种基础语法增强 commons-lang3-3.1.jar 3:版本号 XxxUtils 某某类型的工具类
		 * 如：可以直接判断字符串是否为空
		 * 
		 */

		System.out.println(StringUtils.isNotBlank(null));// false
		System.out.println(StringUtils.isNotBlank(""));// false
		System.out.println(StringUtils.isNotBlank(" "));// false
		System.out.println(StringUtils.isNotBlank("AA"));// true

	}
}
